package com.wsc.it.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

public class HttpClientUtil {

	public static final String OTA_HOTELAVAIL_RQ = "OTA_HotelAvailRQ";

	public static final String OTA_HOTELRES_RQ = "OTA_HotelResRQ";

	public static final String OTA_CANCEL_RQ = "OTA_CancelRQ";

	public static final String OTA_READ_RQ = "OTA_ReadRQ";

	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

	public static String getBodyXml(HttpServletRequest request) throws IOException {
		BufferedReader br = request.getReader();
		String str = "";
		String param = "";
		StringBuilder sb = new StringBuilder();
		while ((str = br.readLine()) != null)
			param = param + str;
		soap(param, sb);
		return sb.toString();
	}
	public static String getBodyJSON(HttpServletRequest request) throws IOException {
		BufferedReader br = request.getReader();
		String str = "";
		String param = "";
		StringBuilder sb = new StringBuilder();
		while ((str = br.readLine()) != null)
			param = param + str;
		soap(param, sb);
		return sb.toString();
	}
	private static void soap(String param, StringBuilder sb) {
		if (param.contains("<soap:Body>")) {
			int starIndex = param.indexOf("<soap:Body>");
			int endIndex = param.indexOf("</soap:Body>");
			String body = param.substring(starIndex + 11, endIndex);
			sb.append(body);
		} else if (param.contains("SOAP-ENV:Body")) {
			int starIndex = param.indexOf("<SOAP-ENV:Body>");
			int endIndex = param.indexOf("</SOAP-ENV:Body>");
			String body = param.substring(starIndex + 15, endIndex);
			sb.append(body);
		} else {
			sb.append(param);
		}
	}

 

	public static String doPost(String httpUrl, String param) {
		StringBuilder result = new StringBuilder();
		HttpURLConnection connection = null;
		OutputStream os = null;
		InputStream is = null;
		BufferedReader br = null;
		try {
			URL url = new URL(httpUrl);
			if ("https".equalsIgnoreCase(url.getProtocol()))
				SslUtils.ignoreSsl();
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setConnectTimeout(15000);
			connection.setReadTimeout(15000);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestProperty("Accept", "*/*");
			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("User-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			connection.setRequestProperty("Content-Type", "application/xml;charset=utf-8");
			if (!StringUtils.isEmpty(param)) {
				os = connection.getOutputStream();
				os.write(param.getBytes("UTF-8"));
			}
			connection.connect();
			if (connection.getResponseCode() == 200) {
				is = connection.getInputStream();
				if (null != is) {
					br = new BufferedReader(new InputStreamReader(is, "utf-8"));
					String temp = null;
					while (null != (temp = br.readLine())) {
						result.append(temp);
						result.append("\r\n");
					}
				}
			}
		} catch (Exception e) {
			logger.error("{}", e.getMessage(), e);
		} finally {
			try {
				if (br != null)
					br.close();
				if (os != null)
					os.close();
				if (is != null)
					is.close();
				if (connection != null)
					connection.disconnect();
			} catch (IOException e) {
				logger.error("finally{}", e.getMessage(), e);
			}
		}
		return result.toString();
	}

	public static String parseSoapHttpBody(HttpServletRequest request, String requestType) {
		String xmlReq = null;
		SAXReader reader = new SAXReader();
		Document document = null;
		try {
			document = reader.read((InputStream) request.getInputStream());
			Element root = document.getRootElement();
			xmlReq = document.asXML();
			Element rqElement = null;
			Element bodyElement = root.element("Body");
			rqElement = bodyElement.element(requestType);
			xmlReq = (rqElement == null) ? null : rqElement.asXML();
		} catch (Exception e) {
			logger.error("document=" + ((null != document) ? document.asXML() : null), e);
		}
		return xmlReq;
	}
	
	public static String parseHttpString(HttpServletRequest request) {
		String callbackMsg = null;
		InputStream is = null;
		try {
			is = request.getInputStream();
			callbackMsg=IOUtil.toString(is);
		} catch (Exception e) {
			logger.error("",callbackMsg, e.getMessage());
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (Exception e2) {
						logger.error("is.close error {}",e2.getMessage());
					}
				}
			}		

		return callbackMsg;
	}
	
	public static Map<String, String> getAllRequestParam( HttpServletRequest request) {
	    Map<String, String> res = new HashMap<String, String>();
	    Enumeration<?> temp = request.getParameterNames();
	    if (null != temp) {
	        while (temp.hasMoreElements()) {
	            String en = (String) temp.nextElement();
	            String value = request.getParameter(en);
	            res.put(en.trim(), value.trim());
	        }
	    }
	    return res;
	}

	
}
